﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;
using Wicresoft.UnifyShow.Business;
using System.Configuration;
using NRemedy.MVC.UI;
using System.IO;
using NPOI.HSSF.UserModel;

namespace Wicresoft.UnifyShow2.Portal
{
    public class BaseController : Controller
    {
        public static string ShowError = ConfigurationManager.AppSettings["ShowError"];
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            //filterContext.Result = View();
            //if (ShowError == "True")
            //{
            //    filterContext.ExceptionHandled = false;
            //}
            //else
            //{
            //    filterContext.Result = Redirect("/Error/ServerError.html");
            //    filterContext.ExceptionHandled = true;
            //}


        }

        protected RawJsonResult RawJson(JsonEncoding encoding)
        {
            return new RawJsonResult() { Data = encoding.ToString(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        //private string _cookieKey;
        ////in order to SSO,this site must be one of the sub-domain like:
        ////unify.fjyc.com
        ////the parent domain or other sub-domain site will set cookie for the parent domain,
        ////and try to get cookie(UNI_SESS).
        ////if cookie exist,indicate user is authenticated.
        ////otherwise return to own login page
        //protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        //{
        //    base.Initialize(requestContext);

        //    if (_cookieKey == null)
        //    {
        //        //get cookie key
        //        _cookieKey = System.Configuration.ConfigurationManager.AppSettings["SSOCookie"];
        //    }

        //    //not set SSOCookie config,don't try SSO Authentication
        //    if (string.IsNullOrEmpty(_cookieKey)) return;

        //    //try get cookie
        //    var cookie = requestContext.HttpContext.Request.Cookies[_cookieKey];
        //    //SSO cookie exsit
        //    if (cookie != null)
        //    {
        //        //has SSO
        //        CreateUserBySSO(cookie);
        //    }
        //    else
        //    {
        //        string user = CustomLoginUtil.GetUser();
        //        if (string.IsNullOrEmpty(user)) return;
        //        User2 = new CustomPrincipal(
        //            user,//cn
        //            string.Empty,//uid
        //            string.Empty,//dept
        //            null,//logintime
        //            ".local"
        //        );
        //    }
        //}

        //protected override void OnAuthorization(AuthorizationContext filterContext)
        //{
        //    if (User2 != null && User2.Identity != null && User2.Identity.IsAuthenticated)
        //        return;
        //    filterContext.Result = new HttpUnauthorizedResult();
        //}

        //private void CreateUserBySSO(HttpCookie sCookie)
        //{
        //    string[] splits = DecryptSSOCookie(sCookie.Value).Split('&');

        //    User2 = new CustomPrincipal(
        //        splits[0],//cn
        //        splits[1],//uid
        //        splits[2],//dept
        //        DateTime.Parse(splits[3]),//logintime
        //        "SSO"
        //    );
        //}

        //private string DecryptSSOCookie(string org)
        //{
        //    //TODO, mock now, wait for decrypt method
        //    return org;

        //}

        protected void SetRoles(IUser_X user)
        {
            UserSiteIDs = new List<decimal>();
            //if (User != null || User2 != null)
            if (User != null)
            {
                //实际通过数据库动态根据 User 来获取相应地Role;
                //string userName = User != null ? User.Identity.Name : User2.Identity.Name;
                UserLoginID = User.Identity.Name;
                UsersSites = user.GetSiteIDByName(UserLoginID).OrderBy(o => o.ID).ToList();
                //Decimal sitesAllCount = user.GetCountOfTheAllSite();
                User_XModel userM = user.GetUser_XByName(UserLoginID);

                if (userM != null && userM.Disabled == 1) userM = null;

                if (userM == null)
                {
                    UserID = -1;
                    return;
                }

                foreach (var item in UsersSites)
                {
                    UserSiteIDs.Add(item.SiteID);
                }

                UserDisplayName = userM.DisplayName;

                // IsAllAdmin = sitesAllCount == UsersSites.Count ? true : false;
                IsConfigAdmin = userM.IsAdmin == 1 ? true : false;
                UserID = userM.ID;
            }
        }

        public string UserLoginID { get; private set; }
        //public IPrincipal User2 { get; private set; }
        public List<decimal> UserSiteIDs { get; private set; }
        // public bool IsAllAdmin;
        public bool IsConfigAdmin { get; private set; }
        public decimal UserID { get; private set; }
        public string UserDisplayName { get; private set; }
        public List<UserAndSiteModel> UsersSites { get; private set; }


        protected HtmlHelper GetHtmlHelper(string viewPageName)
        {
            Stream filter = Stream.Null;
            StreamWriter writer = new StreamWriter(filter);
            var viewContext = new ViewContext(this.ControllerContext,
                new WebFormView(this.ControllerContext, viewPageName),
                new ViewDataDictionary(this.ViewData),
                new TempDataDictionary(), writer);
            return new HtmlHelper(viewContext, new ViewPage());
        }

        /// <summary>
        /// 创建上传文件夹
        /// </summary>
        /// <returns>文件夹绝对路径</returns>
        protected string CreateUploadFilePath()
        {
            var today = DateTime.Today.ToString("yyyyMMdd");
            var guid = Guid.NewGuid().ToString();

            string filePath = Server.MapPath(Path.Combine(ConfigurationManager.AppSettings["PlanUploadFilePath"], today, guid));

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            return filePath;
        }

        /// <summary>
        /// 向浏览器导出文件
        /// </summary>
        /// <param name="fullFilePath">文件的完整路径</param>
        /// <param name="deleteAfterExport">导出之后是否删除本地文件</param>
        protected void ExportFileToResponse(string fullFilePath, bool deleteAfterExport = true)
        {
            string filePath = Path.GetDirectoryName(fullFilePath);
            string fileName = Path.GetFileName(fullFilePath);

            //下载,分块下载缓解服务器压力
            var fileInfo = new FileInfo(fullFilePath);
            if (fileInfo.Exists)
            {
                const long ChunkSize = 4096; //每次下载4k
                byte[] buffer = new byte[ChunkSize];

                Response.Clear();
                using (var fileStream = System.IO.File.OpenRead(fullFilePath))
                {
                    long allLength = fileStream.Length;

                    Response.ContentType = "application/octet-stream";
                    if (Request.UserAgent.ToLower().IndexOf("firefox") == -1)
                    {   //非火狐浏览器(火狐浏览器不需要编码文件名)
                        fileName = HttpUtility.UrlEncode(fileName);
                    }
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

                    while (allLength > 0 && Response.IsClientConnected)
                    {
                        int readLength = fileStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));

                        Response.OutputStream.Write(buffer, 0, readLength);
                        Response.Flush();
                        allLength = allLength - readLength;
                    }

                    
                }
            }

            if (deleteAfterExport && Directory.Exists(filePath))
            {
                Directory.Delete(filePath, true);
            }
        }

    }
}
